package com.example.eamh2system.netty;

import com.example.eamh2system.netty.handler.H2NettyServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class H2NettyServer {

    @Value("${Tcp.port}")
    int port;

    @Autowired
    H2NettyServerHandler h2NettyServerHandler;

    public void start() {
        new Thread(this::run).start();
    }


    public void run() {
        log.info("启动服务端");
        NioEventLoopGroup boosGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(boosGroup,workGroup)
                //设置线程队列连接个数
                .option(ChannelOption.SO_BACKLOG,1024)
                .option(ChannelOption.SO_REUSEADDR, true)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        pipeline.addLast("idleStateHandler",new IdleStateHandler(5,0,0, TimeUnit.SECONDS));
                        pipeline.addLast("channelHandler",h2NettyServerHandler);

                    }
                });
        try {
            log.info("netty server start。。");

            ChannelFuture channelFuture=serverBootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            {
                workGroup.shutdownGracefully();
                boosGroup.shutdownGracefully();
            }
        }
    }
}
